package com.itcast.netty.spring;

import com.itcast.netty.service.BaseService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 业务处理类
 *
 * @author zheng.zhang
 */
@Slf4j
@Component
public class SpringDiscardServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Autowired
    private BaseService baseService;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        try {
            log.info("传输的内容是:{}", byteBuf.toString(CharsetUtil.UTF_8));
            // 调用service服务
            baseService.test();
        } catch (Exception e) {
            log.error("传输出错:{}", e.getMessage());
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 出现异常就关闭
        cause.printStackTrace();
        ctx.close();
    }
}
